<template>
    <div class="resource-container">
        <div class="title">资源文件列表</div>
        <div class="file-list-container">
            <div class="file-item" v-for="file in uploadsFiles" :key="file.path" @click="previewFile(file.path)"
                :class="{ 'unused-file': file.isNoUse }">
                <div class="file-icon">
                    <img v-if="isImageFile(file.name)" :src="getFullImageUrl(file.path)" :alt="file.name"
                        class="file-thumbnail" @error="handleImageError" />
                    <i v-else class="file-icon-font">&#xe69a;</i>
                </div>
                <div class="file-info">
                    <div class="file-name">{{ file.name }}</div>
                    <div class="file-path">{{ file.path }}</div>
                </div>
                <div class="file-status" v-if="file.isNoUse">
                    <span class="unused-tag">未使用</span>
                </div>
                <div class="file-actions">
                    <a-popconfirm v-if="file.isNoUse" title="确定要删除该图片?" ok-text="是" cancel-text="否"
                        @confirm="removeFile(file.path)">
                        <button class="remove-btn" @click.stop="">删除</button>
                    </a-popconfirm>
                </div>
            </div>
            <div class="no-files" v-if="uploadsFiles.length === 0">
                暂无上传文件
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue';
import { inject, onActivated, onMounted, ref } from 'vue';

const imagePreviewRef = inject('imagePreviewRef') as any;
const uploadsFiles = ref<{ name: string, path: string }[]>([]);
const imageUrls = ref<string[]>([]);


const getAllUploads = async () => {
    try {
        const response = await fetch("http://localhost:32068/getAllUploads");
        const data = await response.json();
        uploadsFiles.value = data.data || [];
    } catch (error) {
        console.error("获取上传文件列表失败:", error);
    }
};

// 通过接口获取备忘录数据
const getMemosFromAPI = async () => {
    try {
        const response = await fetch("http://localhost:32068/api/memorys");
        const result = await response.json();
        return result.data || [];
    } catch (error) {
        console.error("获取备忘录数据失败:", error);
        return [];
    }
};

// 通过接口获取日期列表数据
const getDateListFromAPI = async () => {
    try {
        const response = await fetch("http://localhost:32068/api/diarys");
        const result = await response.json();
        return result.data || [];
    } catch (error) {
        console.error("获取日期列表数据失败:", error);
        return [];
    }
};

const getImageUrls = async () => {
    const noteList = await getMemosFromAPI();
    const dataList = await getDateListFromAPI();

    // 提取所有笔记中的图片链接
    const extractImageUrls = (notes: any[]) => {
        const urls = [];
        for (const note of notes) {
            if (note.content) {
                // 使用正则表达式匹配图片标签中的src属性
                const imgRegex = /<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>/g;
                let match;
                while ((match = imgRegex.exec(note.content)) !== null) {
                    urls.push(match[1]);
                }
            }
        }
        return urls;
    };

    imageUrls.value = [
        ...extractImageUrls(noteList),
        ...extractImageUrls(dataList)
    ];

    uploadsFiles.value = uploadsFiles.value.map(file => {
        // 从 path 中提取文件名部分
        const fileNameFromPath = file.path.split('/').pop();

        // 检查是否在任何 imageUrl 中
        const isUsed = imageUrls.value.some(url => {
            const fileNameFromUrl = url.split('/').pop();
            return fileNameFromUrl === file.name || fileNameFromUrl === fileNameFromPath;
        });

        return isUsed ? { ...file, isNoUse: false } : { ...file, isNoUse: true };
    });

};





const isImageFile = (fileName: string): boolean => {
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
    const extension = fileName.split('.').pop()?.toLowerCase() || '';
    return imageExtensions.includes(extension);
};

const getFullImageUrl = (filePath: string): string => {
    return `http://localhost:32068/uploads/${filePath}`;
};

const handleImageError = (event: Event) => {
    const target = event.target as HTMLImageElement;
    target.style.display = 'none';
};

const previewFile = (filePath: string) => {
    // TODO: 实现文件预览功能
    imagePreviewRef.value.open(getFullImageUrl(filePath))
};

const removeFile = async (filePath: string) => {
    try {
        const response = await fetch("http://localhost:32068/deleteFile", {
            method: "DELETE",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ filePath }),
        });

        const result = await response.json();

        if (result.code === 200) {
            // 更新文件列表
            // uploadsFiles.value = result.data || [];
            console.log("文件删除成功");
            message.success("文件删除成功")
            await markHasUse()
        } else {
            console.error("文件删除失败:", result.error);
            message.error("文件删除失败")
        }
    } catch (error) {
        console.error("删除文件时发生错误:", error);
        message.error("文件删除失败")
    }
};


const markHasUse = async () => {
    await getAllUploads()
    await getImageUrls()
    // uploadsFiles  imageUrls
};

onMounted(async () => {
    await markHasUse()
});


onActivated(async () => {
    await markHasUse()
})

</script>

<style scoped>
* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

.resource-container {
    font-family: Arial, sans-serif;
    height: calc(100% - 20px);
    overflow-y: auto;
}

.resource-container>.title {
    color: #333;
    font-size: 16px;
    line-height: 40px;
    padding: 5px 15px;
    margin: 0;
}

.file-list-container {
    display: flex;
    flex-direction: column;
    gap: 10px;
    font-size: 15px;
    padding: 12px 15px;
    height: calc(100% - 60px);
    overflow-y: auto;
}

.file-item {
    display: flex;
    align-items: center;
    padding: 15px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    background-color: #fff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
    cursor: pointer;
}

.file-item:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-color: #007bff;
}

.file-icon {
    margin-right: 15px;
    width: 48px;
    height: 48px;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.file-thumbnail {
    max-width: 100%;
    max-height: 100%;
    object-fit: cover;
    border-radius: 4px;
    cursor: pointer;
}

.file-icon-font {
    font-family: "iconfont" !important;
    font-size: 24px;
    font-style: normal;
    color: #007bff;
}

.file-info {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.file-name {
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
    font-size: 14px;
}

.file-path {
    color: #666;
    font-size: 13px;
}

.file-status {
    margin-left: 15px;
    display: flex;
    gap: 10px;
    padding-right: 20px;
}

.unused-tag {
    background-color: #f8d7da;
    color: #721c24;
    padding: 4px 8px;
    border-radius: 4px;
}

.file-actions {
    margin-left: 15px;
    display: flex;
    gap: 10px;
    padding-right: 20px;
}

.preview-btn {
    padding: 8px 16px;
    background-color: transparent;
    color: #007bff;
    border: 1px solid #007bff;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
}

.preview-btn:hover {
    background-color: rgba(0, 123, 255, 0.1);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
}

.remove-btn {
    padding: 8px 16px;
    background-color: transparent;
    color: #dc3545;
    border: 1px solid #dc3545;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
}

.remove-btn:hover {
    background-color: rgba(220, 53, 69, 0.1);
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(220, 53, 69, 0.3);
}

.unused-file {
    opacity: 0.7;
    border-left: 3px solid #ffc107;
}

.no-files {
    text-align: center;
    padding: 40px 20px;
    color: #999;
    font-size: 16px;
}
</style>